package com.hanson.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hanson.Const;
import com.hanson.common.bean.TaskBean;
import com.hanson.common.service.RedisService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class TaskService {
    @Autowired
    private RedisService redisService;

    public List<TaskBean> getAllTask() {
        Set<String> keysSet = redisService.keys("Task");
        if (CollectionUtils.isNotEmpty(keysSet)) {
            List<TaskBean> taskBeanList = new ArrayList<>();
            for (String key : keysSet) {
                Object taskObj = redisService.get(key);
                if (null != taskObj) {
                    taskBeanList.add(JSONObject.parseObject(String.valueOf(taskObj), TaskBean.class));
                }
            }
            return taskBeanList;
        }
        return null;
    }


    public void saveTask(TaskBean taskBean) {
        String redisKey = String.format(Const.TASK_KEY, taskBean.getJobType(), taskBean.getJobId());
        redisService.set(redisKey, JSON.toJSONString(taskBean));
    }

    public void deleteTask(Integer jobType, String jobId) {
        String redisKey = String.format(Const.TASK_KEY, jobType, jobId);
        redisService.del(redisKey);
    }
}
